#include "common.h"
#import "NVADocumentController.h"
#import "NVALibraryController.h"

static void showAlert(NSString *msg, NSString *filename)
{
	UIAlertView *alert = [[UIAlertView alloc]
		initWithTitle: msg
		message: filename
		delegate: nil
		cancelButtonTitle: @"Okay"
		otherButtonTitles: nil];
	[alert show];
	[alert release];
}

@implementation NVALibraryController

- (void) viewWillAppear: (BOOL)animated
{
	[self setTitle: @"NVA Documents"];
	[self reload];
	printf("library viewWillAppear (starting reload timer)\n");
	timer = [NSTimer timerWithTimeInterval: 3
		target: self selector: @selector(reload) userInfo: nil
		repeats: YES];
	[[NSRunLoop currentRunLoop] addTimer: timer forMode: NSDefaultRunLoopMode];
    dropBox = [self resourceBasedButton:@"dropbox" withAction:@selector(onDropBox:)];
    [[self navigationItem] setRightBarButtonItems:[NSArray arrayWithObjects:dropBox, nil]];
}

- (void) viewWillDisappear: (BOOL)animated
{
	printf("library viewWillDisappear (stopping reload timer)\n");
	[timer invalidate];
	timer = nil;
}

- (void) reload
{
	if (files) {
		[files release];
		files = nil;
	}
    
	NSFileManager *fileman = [NSFileManager defaultManager];
	NSString *docdir = [NSString stringWithFormat: @"%@/Documents", NSHomeDirectory()];
	NSMutableArray *outfiles = [[NSMutableArray alloc] init];
	NSDirectoryEnumerator *direnum = [fileman enumeratorAtPath:docdir];
	NSString *file;
	BOOL isdir;
	while (file = [direnum nextObject]) {
		NSString *filepath = [docdir stringByAppendingPathComponent:file];
		NSLog(@"file %@\n", file);
		if ([fileman fileExistsAtPath:filepath isDirectory:&isdir] && !isdir) {
			[outfiles addObject:file];
		}
	}
    
	files = outfiles;
    
	[[self tableView] reloadData];
}

- (void) dealloc
{
	[doc release];
	[files release];
    [dropBox release];
    dropBox = nil;
	[super dealloc];
}

- (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)o
{
	return YES;
}

- (NSInteger) numberOfSectionsInTableView: (UITableView*)tableView
{
	return 1;
}

- (NSInteger) tableView: (UITableView*)tableView numberOfRowsInSection: (NSInteger)section
{
	return [files count];
}

- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == [actionSheet destructiveButtonIndex])
	{
		char filename[PATH_MAX];
		int row = [actionSheet tag];
        
		dispatch_sync(queue, ^{});
        
		strcpy(filename, [NSHomeDirectory() UTF8String]);
		strcat(filename, "/Documents/");
		strcat(filename, [[files objectAtIndex: row] UTF8String]);
        
		printf("delete document '%s'\n", filename);
        
		unlink(filename);
        
		[self reload];
	}

}

- (void) onTapDelete: (UIControl*)sender
{
    int row = [sender tag];
	NSString *title = [NSString stringWithFormat: @"Delete %@?", [files objectAtIndex:row]];
	UIActionSheet *sheet = [[UIActionSheet alloc]
							initWithTitle: title
							delegate: self
							cancelButtonTitle: @"Cancel"
							destructiveButtonTitle: @"Delete"
							otherButtonTitles: nil];
	[sheet setTag: row];
	[sheet showInView: [self tableView]];
	[sheet release];
}

- (UITableViewCell*) tableView: (UITableView*)tableView cellForRowAtIndexPath: (NSIndexPath*)indexPath
{
	static NSString *cellid = @"MuCellIdent";
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: cellid];
	if (!cell)
		cell = [[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier: cellid] autorelease];
	int row = [indexPath row];
	[[cell textLabel] setText: [files objectAtIndex: row]];
	[[cell textLabel] setFont: [UIFont systemFontOfSize: 20]];
    
	UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
	[deleteButton setImage: [UIImage imageNamed: @"x_alt_blue.png"] forState: UIControlStateNormal];
	[deleteButton setFrame: CGRectMake(0, 0, 35, 35)];
	[deleteButton addTarget: self action: @selector(onTapDelete:) forControlEvents: UIControlEventTouchUpInside];
	[deleteButton setTag: row];
	[cell setAccessoryView: deleteButton];
    
	return cell;
}

- (void) tableView: (UITableView*)tableView didSelectRowAtIndexPath: (NSIndexPath*)indexPath
{
	int row = [indexPath row];
	[self openDocument: [files objectAtIndex: row]];
}

static NSString *alteredfilename(NSString *name, int i)
{
	if (i == 0)
		return name;
    
	NSString *nam = [name stringByDeletingPathExtension];
	NSString *e = [name pathExtension];
	return [[[NSString alloc] initWithFormat:@"%@(%d).%@", nam, i, e] autorelease];
}

static NSString *moveOutOfInbox(NSString *docpath)
{
	if ([docpath hasPrefix:@"Inbox/"])
	{
		NSFileManager *fileMan = [NSFileManager defaultManager];
		NSString *base = [docpath stringByReplacingOccurrencesOfString:@"Inbox/" withString:@""];
        
		for (int i = 0; YES; i++)
		{
			NSString *newname = alteredfilename(base, i);
			NSString *newfullpath = [NSString pathWithComponents:[NSArray arrayWithObjects:NSHomeDirectory(), @"Documents", newname, nil]];
            
			if (![fileMan fileExistsAtPath:newfullpath])
			{
				NSString *fullpath = [NSString pathWithComponents:[NSArray arrayWithObjects:NSHomeDirectory(), @"Documents", docpath, nil]];
				[fileMan copyItemAtPath:fullpath toPath:newfullpath error:nil];
				[fileMan removeItemAtPath:fullpath error:nil];
				return newname;
			}
		}
	}
    
	return docpath;
}

- (void) openDocument: (NSString*)nsfilename
{
	nsfilename = moveOutOfInbox(nsfilename);
	NSString *nspath = [[NSArray arrayWithObjects:NSHomeDirectory(), @"Documents", nsfilename, nil]
                        componentsJoinedByString:@"/"];
	_filePath = malloc(strlen([nspath UTF8String])+1);
	if (_filePath == NULL) {
		showAlert(@"Out of memory in openDocument", nsfilename);
		return;
	}
    
	strcpy(_filePath, [nspath UTF8String]);
    
	dispatch_sync(queue, ^{});
    
	printf("open document '%s'\n", _filePath);
    
	_filename = [nsfilename retain];
	[doc release];
	doc = [[NVADocRef alloc] initWithFilename:_filePath];
	if (!doc) {
		showAlert(@"Cannot open document", nsfilename);
		return;
	}
    
	if (fz_needs_password(doc->doc))
		[self askForPassword: @"'%@' needs a password:"];
	else
		[self onPasswordOkay];
}

- (void) askForPassword: (NSString*)prompt
{
	UIAlertView *passwordAlertView = [[UIAlertView alloc]
                                      initWithTitle: @"Password Protected"
                                      message: [NSString stringWithFormat: prompt, [_filename lastPathComponent]]
                                      delegate: self
                                      cancelButtonTitle: @"Cancel"
                                      otherButtonTitles: @"Done", nil];
	[passwordAlertView setAlertViewStyle: UIAlertViewStyleSecureTextInput];
	[passwordAlertView show];
	[passwordAlertView release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	char *password = (char*) [[[alertView textFieldAtIndex: 0] text] UTF8String];
	[alertView dismissWithClickedButtonIndex: buttonIndex animated: TRUE];
	if (buttonIndex == 1) {
		if (fz_authenticate_password(doc->doc, password))
			[self onPasswordOkay];
		else
			[self askForPassword: @"Wrong password for '%@'. Try again:"];
	} else {
		[self onPasswordCancel];
	}
}

- (void) onPasswordOkay
{
	NVADocumentController *document = [[NVADocumentController alloc] initWithFilename: _filename path:_filePath document: doc];
	if (document) {
		[self setTitle: @"Library"];
		[[self navigationController] pushViewController: document animated: YES];
		[document release];
	}
	[_filename release];
	free(_filePath);
}

- (void) onPasswordCancel
{
	[_filename release];
	free(_filePath);
	printf("close document (password cancel)\n");
}


- (UIBarButtonItem *) resourceBasedButton:(NSString *)resource withAction:(SEL)selector
{
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
	{
		//return [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:resource ofType:@"png"]] style:UIBarButtonItemStylePlain target:self action:selector];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setBackgroundImage:[UIImage imageNamed:resource] forState:0];
        [btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
        if ([@"dropbox" isEqualToString:resource]) {
            btn.frame = CGRectMake(0, 0, 32, 32);
        }else{
            btn.frame = CGRectMake(0, 0, 24, 24);
        }
        [btn setContentMode:UIViewContentModeScaleAspectFill];
        UIBarButtonItem *ib = [[UIBarButtonItem alloc] initWithCustomView:btn];
        return ib;
        
	}
	else
	{
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setBackgroundImage:[UIImage imageNamed:resource] forState:0];
        [btn addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
        if ([@"dropbox" isEqualToString:resource]) {
            btn.frame = CGRectMake(0, 0, 32, 32);
        }
        else{
            btn.frame = CGRectMake(0, 0, 24, 24);
        }
        [btn setContentMode:UIViewContentModeScaleAspectFill];
        UIBarButtonItem *ib = [[UIBarButtonItem alloc] initWithCustomView:btn];
        return ib;
	}
}
- (void) onDropBox: (id)sender
{
    DropboxBrowserViewController *dropboxBrowser = [[DropboxBrowserViewController alloc] init];
    [[self navigationController] pushViewController: dropboxBrowser animated: YES];
    dropboxBrowser.allowedFileTypes = @[@"nva"]; // Uncomment to filter file types. Create an array of allowed types. To allow all file types simply don't set the property
    // dropboxBrowser.tableCellID = @"DropboxBrowserCell"; // Uncomment to use a custom UITableViewCell ID. This property is not required
    
    // When a file is downloaded (either successfully or unsuccessfully) you can have DBBrowser notify the user with Notification Center. Default property is NO.
    dropboxBrowser.deliverDownloadNotifications = YES;
    
    // Dropbox Browser can display a UISearchBar to allow the user to search their Dropbox for a file or folder. Default property is NO.
    dropboxBrowser.shouldDisplaySearchBar = YES;
    
    // Set the delegate property to recieve delegate method calls
    dropboxBrowser.rootViewDelegate = self;
}


- (void)dropboxBrowser:(DropboxBrowserViewController *)browser didDownloadFile:(NSString *)fileName didOverwriteFile:(BOOL)isLocalFileOverwritten {
    if (isLocalFileOverwritten == YES) {
        NSLog(@"Downloaded %@ by overwriting local file", fileName);
    } else {
        NSLog(@"Downloaded %@ without overwriting", fileName);
    }
}

- (void)dropboxBrowser:(DropboxBrowserViewController *)browser didFailToDownloadFile:(NSString *)fileName {
    NSLog(@"Failed to download %@", fileName);
}

- (void)dropboxBrowser:(DropboxBrowserViewController *)browser fileConflictWithLocalFile:(NSURL *)localFileURL withDropboxFile:(DBMetadata *)dropboxFile withError:(NSError *)error {
    NSLog(@"File conflict between %@ and %@\n%@ last modified on %@\nError: %@", localFileURL.lastPathComponent, dropboxFile.filename, dropboxFile.filename, dropboxFile.lastModifiedDate, error);
}

- (void)dropboxBrowserDismissed:(DropboxBrowserViewController *)browser {
    // This method is called after Dropbox Browser is dismissed. Do NOT dismiss DropboxBrowser from this method
    // Perform any UI updates here to display any new data from Dropbox Browser
    // ex. Update a UITableView that shows downloaded files or get the name of the most recently selected file:
    //     NSString *fileName = [DropboxBrowserViewController currentFileName];
}

- (void)dropboxBrowser:(DropboxBrowserViewController *)browser deliveredFileDownloadNotification:(UILocalNotification *)notification {
    long badgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber]+1;
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badgeNumber];
}


@end
